package com.geeyuu.android.service;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

import com.geeyuu.android.GeeConfig;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.model.ChatInfo;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.LogUtil;

public class SendMsgHandle {
    private static final String TAG = "SendMsgHandle";

    /**
     * 处理界面发送到service的消息
     * 
     * @param msg
     * @return
     */
    public static RECmd handleSendMsg(Context context, Message msg) {
        // 获取bundle的值一律使用getString()
        Bundle bundle = msg.getData();
        RECmd reCmd = new RECmd(context);
        reCmd.cmd = msg.what;
        reCmd.tag = (String)msg.obj;

        // ===================================双横线内编码====================================
        // 这里代码的约定
        // 处理业务过程遇到任何错误、异常、不符合逻辑等等情况，一律返回RECmd.PARSE_ERROR
        // 处理业务过程完全按照正常逻辑走，返回RECmd.PARSE_OK
        // reCmd需要做的就只有一个事情，给jsonStr赋值
        switch (msg.what) {
        case ProtocolCommand.CMD_REGISTER: // 注册
            reCmd.parseError = handleRegister(context, bundle, reCmd);
            break;
        case ProtocolCommand.CMD_LOGIN: // 登录
            reCmd.parseError = handleLogin(context, bundle, reCmd);
            break;
        case ProtocolCommand.CMD_MODIFY_PASSWORD: // 修改密码
            break;
        case ProtocolCommand.CMD_SET_PHOTO:
            break;
        case ProtocolCommand.CMD_SET_MY_USER_INFO:
            reCmd.parseError = handleSetUserInfo(context, bundle, reCmd); //设置个人信息
            break;
        case ProtocolCommand.CMD_INVITE_FOR_REGISTER:
            break;
        case ProtocolCommand.CMD_OFFLINE_RESET_PASSWORD:
            break;
        case ProtocolCommand.CMD_GET_MY_USERNAME:
            break;
        case ProtocolCommand.CMD_QUERY_USER_BASE_INFO:
            break;
        case ProtocolCommand.CMD_QUERY_GROUP_USER_BASE_INFO:
            break;
        case ProtocolCommand.CMD_QUERY_USER_INFO:
            reCmd.parseError = handleQueryUserInfo(context, bundle, reCmd); //请求用户信息
            break;
        case ProtocolCommand.CMD_QUERY_USER_EXT_INFO:
            break;
        case ProtocolCommand.CMD_QUERY_AROUND_USERS_28_SIZE:
            reCmd.parseError = handleGetAroundUser(context, bundle, reCmd); //请求周边好友
            break;
        case ProtocolCommand.CMD_SET_INTEREST:
            
            break;
        case ProtocolCommand.CMD_SET_BLACK:
            break;
        case ProtocolCommand.CMD_QUERY_MY_USER_LIST:
            break;
        case ProtocolCommand.CMD_QUERY_MY_FANS:
            break;
        case ProtocolCommand.CMD_QUERY_ALBUM: 
            reCmd.parseError = handleQueryAlbum(context, bundle, reCmd); //请求 某人相册列表
            break;
        case ProtocolCommand.CMD_ADD_TO_ALBUM:
            reCmd.parseError = handleAddAlbum(context, bundle, reCmd); //请求 增删照片
            break;
        case ProtocolCommand.CMD_SEND_FLOWER:
            break;
        case ProtocolCommand.CMD_REPORT:
            break;
        case ProtocolCommand.CMD_INVATE_FOR_SHARE:
            break;
        case ProtocolCommand.CMD_RESPONSE_FOR_SHARE:
            break;
        case ProtocolCommand.CMD_RELEASE_SHARE:
            break;
        case ProtocolCommand.CMD_SHAKE_SHAKE:
            reCmd.parseError = handleShakeShake(context, bundle, reCmd); //请求 摇一摇用户
            break;
        case ProtocolCommand.CMD_REPORT_LOCATION:
            break;
        case ProtocolCommand.CMD_SEND_CHAT_MSG:
            reCmd.parseError = handleSendChatMsg(context, bundle, reCmd); //发送聊天信息
            break;
        case ProtocolCommand.CMD_PRIVATE_MSG_RECEIVED:
            break;
        case ProtocolCommand.CMD_SYSTEM_MSG_RECEIVED:
            break;
//        case ProtocolCommand.CMD_HEART_BEAT:
//            break;
        case ProtocolCommand.CMD_REMOVE_CHAT_MSG_RECORD:
            break;
        default:
            LogUtil.e(TAG, "activity发来一个不存在的command");
            break;

        }
        // ===================================================================================

        return reCmd;
    }
    
    private static int handleSendChatMsg(Context context, Bundle bundle, RECmd reCmd) {
        
        int chatMsgType = bundle.getInt("chatMsgType");
        long sendUid = GeePrefrence.getMyUid(context);
        long recUid = bundle.getLong("friendUid");
        String content = bundle.getString("msgContent");
        
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.chatContent = content;
        chatInfo.friendUid = recUid;
        chatInfo.msgType = chatMsgType;
        chatInfo.recUid = recUid;
        chatInfo.sendUid = sendUid;
        long msgId = chatInfo.saveChatInfo(context);
        if(msgId == -1){
            LogUtil.e(TAG, "聊天信息插入数据库失败");
            return RECmd.PARSE_ERROR;
        }
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("chat_msg_type", chatMsgType);
            jsonObject.put("send_uid", sendUid);
            jsonObject.put("recv_uid", recUid);
            jsonObject.put("send_time", 0);
            jsonObject.put("chat_msg_id", msgId);
            if(chatMsgType == ChatInfo.MSG_TYPE_VOICE){
                //上传文件，获取returnId，更新数据库，然后才发送出去
                
                
                
                
                return RECmd.PARSE_ERROR;
            }else if(chatMsgType == ChatInfo.MSG_TYPE_LOCATION){
                String[] locArray = chatInfo.lonAndLat.split(",");
                JSONObject locJO = new JSONObject();
                locJO.put("longitude", locArray[0]);
                locJO.put("latitude", locArray[1]);
                jsonObject.put("location", locJO);
            }
            reCmd.jsonStr = "{\"chat_msg\":" + jsonObject.toString() + "}";
            LogUtil.d(TAG, "发送聊天json: " + reCmd.jsonStr);
            return RECmd.PARSE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "发送聊天信息组装异常", e);
            return RECmd.PARSE_ERROR;
        }
    }

    private static int handleShakeShake(Context context, Bundle bundle, RECmd reCmd) {
        String[] loc = bundle.getStringArray("locArray");
        if(null != loc && loc.length == 2){
            JSONObject jo = new JSONObject();
            try {
                jo.put("longitude", loc[0]);
                jo.put("latitude", loc[1]);
                reCmd.jsonStr = "{\"location\":" + jo.toString() + "}";
                return RECmd.PARSE_OK;
            } catch (JSONException e) {
                LogUtil.e(TAG, "组装json异常", e);
            }
        }else{
            LogUtil.e(TAG, "参数不正确");
        }
        return RECmd.PARSE_ERROR;
    }

    private static int handleAddAlbum(Context context, Bundle bundle, RECmd reCmd) {
        String type = bundle.getString(DataKey.S_KEY_PHOTO_TYPE);
        String opt = bundle.getString(DataKey.S_KEY_PHOTO_ACTION);
        String pId = bundle.getString(DataKey.S_KEY_PHOTO_ID);
        
        if(CommonUtil.isEmpty(type) || CommonUtil.isEmpty(opt) || CommonUtil.isEmpty(pId)){
            LogUtil.e(TAG, "组装增添相册json的参数不正确");
            return RECmd.PARSE_ERROR;
        }
        
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", type);
            jsonObject.put("opt", opt);
            jsonObject.put("photo_id", pId);
            reCmd.jsonStr = jsonObject.toString();
            LogUtil.d(TAG, "增添相册json: " + reCmd.jsonStr);
            return RECmd.PARSE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "组装增添相册json异常", e);
            return RECmd.PARSE_ERROR;
        }
    }

    private static int handleQueryAlbum(Context context, Bundle bundle, RECmd reCmd) {
        String friendUid = bundle.getString(DataKey.S_KEY_USER_PHOTO_QUERY_UID);
        String pageIndex = bundle.getString(DataKey.S_KEY_USER_PHOTO_QUERY_PAGE_INDEX);
        String type = bundle.getString(DataKey.S_KEY_USER_PHOTO_QUERY_TYPE);
        if(CommonUtil.isEmpty(friendUid) || CommonUtil.isEmpty(pageIndex) || CommonUtil.isEmpty(type)){
            LogUtil.e(TAG, "组装获取用户相册json的参数不正确");
            return RECmd.PARSE_ERROR;
        }
        JSONObject jo = new JSONObject();
        try {
            jo.put("uid", friendUid);
            jo.put("page_index", pageIndex);
            jo.put("type", type);
            reCmd.jsonStr = jo.toString();
            LogUtil.d(TAG, "获取用户相册json: " + reCmd.jsonStr);
            return RECmd.PARSE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "组装获取用户相册json", e);
            return RECmd.PARSE_ERROR;
        }
    }

    private static int handleQueryUserInfo(Context context, Bundle bundle, RECmd reCmd) {
        String queryUserId = bundle.getString(DataKey.S_KEY_QUERY_USER_INFO_UID);
        if(CommonUtil.isEmpty(queryUserId)){
            LogUtil.e(TAG, "请求用户信息，参数uid为空");
            return RECmd.PARSE_ERROR;
        }
        reCmd.jsonStr = "{\"uid\":" + queryUserId + "}";
        return RECmd.PARSE_OK;
    }

    private static int handleGetAroundUser(Context context, Bundle bundle, RECmd reCmd) {
        
        String lonAndLat = bundle.getString(DataKey.S_KEY_LON_AND_LAT);
        String orderBy = bundle.getString(DataKey.S_KEY_ORDER_BY);
        String roleFilter = bundle.getString(DataKey.S_KEY_ROLE_FILTER);
        String onlineFilter = bundle.getString(DataKey.S_KEY_ONLINE_FILTER);
        String pageIndex = bundle.getString(DataKey.S_KEY_PAGE_INDEX);
        
        if(CommonUtil.isEmpty(lonAndLat) || CommonUtil.isEmpty(orderBy) || CommonUtil.isEmpty(roleFilter) || CommonUtil.isEmpty(onlineFilter) || CommonUtil.isEmpty(pageIndex)){
            LogUtil.e(TAG, "请求周边好友参数不正确");
            return RECmd.PARSE_ERROR;
        }
        
        String[] loc = lonAndLat.split(",");
        JSONObject locJO = new JSONObject();
        try {
            locJO.put("longitude", loc[0]);
            locJO.put("latitude", loc[1]);
        }catch (Exception e) {
            LogUtil.e(TAG, "handleGetAroundUser()");
            return RECmd.PARSE_ERROR;
        }
        JSONObject jo = new JSONObject();
        try {
            jo.put("location", locJO);
            jo.put("sort_type", orderBy);
            jo.put("role_filter", roleFilter);
            jo.put("online_filter", onlineFilter);
            jo.put("page_index", pageIndex);
            reCmd.jsonStr = jo.toString();
            Log.d(TAG, "请求周边用户json: " + reCmd.jsonStr);
            return RECmd.PARSE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "handleGetAroundUser()");
            return RECmd.PARSE_ERROR;
        }
    }

    private static int handleSetUserInfo(Context context, Bundle bundle, RECmd reCmd) {

        String nickName = bundle.getString(DataKey.S_KEY_USERINFO_NICKNAME);
        String age = bundle.getString(DataKey.S_KEY_USERINFO_AGE);
        String height = bundle.getString(DataKey.S_KEY_USERINFO_HEIGHT);
        String weight = bundle.getString(DataKey.S_KEY_USERINFO_WEIGHT);
        String role = bundle.getString(DataKey.S_KEY_USERINFO_ROLE);
        String mainPhotoId = bundle.getString(DataKey.S_KEY_USERINFO_MAIN_PHOTO_ID);
        String sign = bundle.getString(DataKey.S_KEY_USERINFO_SIGN);

        try {
            ContentValues cv = new ContentValues();
            cv.put(BaseUserInfo.EXTRA_UID, GeePrefrence.getMyUid(context));
            
            JSONObject jo = new JSONObject();
            if (null != nickName && nickName.length() > 0) {
                jo.put("nick_name", nickName);
                cv.put(BaseUserInfo.EXTRA_NICK_NAME, nickName);
            }
            if (null != age && age.length() > 0) {
                jo.put("user_age", age);
                cv.put(BaseUserInfo.EXTRA_AGE, age);
            }
            if (null != height && height.length() > 0) {
                jo.put("user_height", height);
                cv.put(BaseUserInfo.EXTRA_HEIGHT, height);
            }
            if (null != weight && weight.length() > 0) {
                jo.put("user_weight", weight + "0");
                cv.put(BaseUserInfo.EXTRA_WEIGHT, weight + "0");
            }
            if (null != role && role.length() > 0) {
                jo.put("user_role", role);
                cv.put(BaseUserInfo.EXTRA_ROLE, role);
            }
            if (null != mainPhotoId && mainPhotoId.length() > 0) {
                jo.put("main_photo_id", mainPhotoId);
                cv.put(BaseUserInfo.EXTRA_MAIN_PHOTO_ID, mainPhotoId);
            }
            if (null != sign && sign.length() > 0) {
                jo.put("user_sign", sign);
                cv.put(BaseUserInfo.EXTRA_SIGN, sign);
            }
            
            if(cv.size() > 1){
                BaseUserInfo.saveOrUpdateUserInfo(context, cv);
            }
            
            if(jo.length() > 0){
                reCmd.jsonStr = "{\"info\":" + jo.toString() + "}";
                Log.d(TAG, "修改个人信息json: " + reCmd.jsonStr);
                return RECmd.PARSE_OK;
            }else{
                Log.e(TAG, "没有需要修改的字段");
                return RECmd.PARSE_ERROR;
            }
        } catch (JSONException e) {
            LogUtil.e(TAG, "组装注册JSON有异常，停止设置注册信息", e);
            return RECmd.PARSE_ERROR;
        }
    }

    private static int handleRegister(Context context, Bundle bundle, RECmd reCmd) {

        String isGuest = bundle.getString(DataKey.S_KEY_IS_GUEST);
        String account = bundle.getString(DataKey.S_KEY_REGISTER_ACCOUNT);
        String password = bundle.getString(DataKey.S_KEY_REGISTER_PASSWORD);

        if (null == isGuest) {
            LogUtil.e(TAG, "activity传过来的参数有异常");
            return RECmd.PARSE_ERROR;
        }

        String deviceId = AndroidUtil.getDeviceId(context);
        if (deviceId == null) {
            LogUtil.e(TAG, "获取设备ID，MAC地址都失败，设备必定是断网，终止注册");
            return RECmd.PARSE_ERROR;
        }

        final String clientVersion = GeeConfig.appVersion;
        final String platform = "a";
        final String nickName = "";

        if (isGuest.equals(DataKey.S_VALUE_REGISTER_IS_GUEST)) { // 是游客
            account = deviceId;
            password = "111111";
        } else {
            password = CommonUtil.getMD5(password);
        }

        if (null == account || null == password) {
            LogUtil.e(TAG, "activity传过来的参数有异常");
            return RECmd.PARSE_ERROR;
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("account", account);
            jsonObject.put("password", password);
            jsonObject.put("client_ver", clientVersion);
            jsonObject.put("phone_id", deviceId);
            jsonObject.put("platform", platform);
            jsonObject.put("nick_name", nickName);
            jsonObject.put("is_guest", isGuest);
            reCmd.jsonStr = jsonObject.toString();
            Log.d(TAG, "注册json: " + reCmd.jsonStr);
            return RECmd.PARSE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "组装注册JSON有异常，停止注册", e);
            return RECmd.PARSE_ERROR;
        }
    }

    private static int handleLogin(Context context, Bundle bundle, RECmd reCmd) {
        final String isGuest = bundle.getString(DataKey.S_KEY_IS_GUEST);

        if (null == isGuest) {
            LogUtil.e(TAG, "activity传过来的参数有异常");
            return RECmd.PARSE_ERROR;
        }

        final String type = bundle.getString(DataKey.S_KEY_LOGIN_TYPE);
        String account = bundle.getString(DataKey.S_KEY_LOGIN_ACCOUNT);
        String password = bundle.getString(DataKey.S_KEY_LOGIN_PASSWORD);

        String deviceId = AndroidUtil.getDeviceId(context);
        if (deviceId == null) {
            LogUtil.e(TAG, "获取设备ID，MAC地址都失败，设备必定是断网，终止注册");
            return RECmd.PARSE_ERROR;
        }

        if (isGuest.equals(DataKey.S_VALUE_REGISTER_IS_GUEST)) { // 是游客
            account = deviceId;
            password = "111111";
        } else {
            password = CommonUtil.getMD5(password);
        }

        if (null == account || null == password || null == type) {
            LogUtil.e(TAG, "activity传过来的参数有异常");
            return RECmd.PARSE_ERROR;
        }

        GeePrefrence.setAccountName(context, account);
        GeePrefrence.setPWD(context, password);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", type);
            jsonObject.put("account", account);
            jsonObject.put("password", password);
            reCmd.jsonStr = jsonObject.toString();
            Log.d(TAG, "登录json: " + reCmd.jsonStr);
            return RECmd.PARSE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "组装登录JSON有异常，停止登录", e);
            return RECmd.PARSE_ERROR;
        }
    }

//    private static int handleModifyPsd(Context context, Bundle bundle, RECmd reCmd) {
//        final String type = bundle.getString(DataKey.S_KEY_LOGIN_TYPE);
//        final String account = bundle.getString(DataKey.S_KEY_LOGIN_ACCOUNT);
//        final String password = bundle.getString(DataKey.S_KEY_LOGIN_PASSWORD);
//        JSONObject jsonObject = new JSONObject();
//
//        try {
//            jsonObject.put("type", type);
//            jsonObject.put("account", account);
//            jsonObject.put("password", password);
//            reCmd.cmd = ProtocolCommand.CMD_LOGIN;
//            reCmd.jsonStr = jsonObject.toString();
//
//            return RECmd.PARSE_OK;
//        } catch (JSONException e) {
//            LogUtil.e(TAG, "组装注册JSON有异常，停止注册", e);
//            return RECmd.PARSE_ERROR;
//        }
//    }
    
    
}
